const fs = require('fs');
const path = require('path');
const { DataSource } = require('typeorm');

// 数据库配置
const dataSource = new DataSource({
    type: 'mysql',
    host: '43.143.253.188',
    port: 3306,
    username: 'nextjs',
    password: 'yEAiRE2jcxTyRBy5',
    database: 'nextjs',
    entities: [],
    synchronize: false,
    logging: false
});

async function importEquipmentBase() {
    try {
        await dataSource.initialize();
        console.log('✅ 数据库连接成功');

        // 读取装备数据文件
        const equipmentDataPath = path.join(__dirname, '..', 'output', 'equipment_base_imported.json');

        if (!fs.existsSync(equipmentDataPath)) {
            throw new Error(`装备数据文件不存在: ${equipmentDataPath}`);
        }

        const equipmentData = JSON.parse(fs.readFileSync(equipmentDataPath, 'utf8'));
        console.log(`📊 读取到 ${equipmentData.data.length} 个装备数据`);

        // 检查是否需要创建装备基础表
        let tableExists = false;
        try {
            const result = await dataSource.query(`
        SELECT COUNT(*) as count 
        FROM information_schema.tables 
        WHERE table_schema = 'nextjs' 
        AND table_name = 'equipment_base'
      `);
            tableExists = result[0].count > 0;
        } catch (error) {
            console.log('🔍 检查表是否存在时出错，将尝试创建表...');
        }

        if (!tableExists) {
            console.log('🔨 创建 equipment_base 表...');
            try {
                await dataSource.query(`
          CREATE TABLE equipment_base (
            id INT PRIMARY KEY,
            name VARCHAR(100) NOT NULL COMMENT '装备名称',
            base INT NOT NULL COMMENT '基础类型',
            level INT NOT NULL COMMENT '等级',
            price VARCHAR(20) NOT NULL COMMENT '价格',
            type INT NOT NULL COMMENT '装备类型',
            image VARCHAR(100) NOT NULL COMMENT '图片',
            intro TEXT COMMENT '介绍',
            weight INT NOT NULL DEFAULT 0 COMMENT '重量',
            req_level INT NOT NULL DEFAULT 0 COMMENT '需求等级',
            req_strength INT NOT NULL DEFAULT 0 COMMENT '需求力量',
            req_constitution INT NOT NULL DEFAULT 0 COMMENT '需求体质',
            req_agility INT NOT NULL DEFAULT 0 COMMENT '需求敏捷',
            req_intelligence INT NOT NULL DEFAULT 0 COMMENT '需求智力',
            bonus_attack INT NOT NULL DEFAULT 0 COMMENT '攻击加成',
            bonus_hp INT NOT NULL DEFAULT 0 COMMENT '血量加成',
            bonus_mp INT NOT NULL DEFAULT 0 COMMENT '魔法加成',
            bonus_defense INT NOT NULL DEFAULT 0 COMMENT '防御加成',
            created_at DATETIME NOT NULL COMMENT '创建时间',
            updated_at DATETIME NULL COMMENT '更新时间'
          ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='装备基础表'
        `);
                console.log('✅ equipment_base 表创建成功');
                tableExists = true;
            } catch (error) {
                console.error('❌ 创建表失败:', error.message);
                throw error;
            }
        } else {
            console.log('✅ equipment_base 表已存在');
        }

        // 清空现有数据（如果表存在）
        if (tableExists) {
            console.log('🗑️ 清空现有装备数据...');
            await dataSource.query('DELETE FROM equipment_base');
            console.log('✅ 现有数据已清空');
        }

        // 导入新数据
        console.log('📥 开始导入装备数据...');
        let successCount = 0;
        let errorCount = 0;

        for (const equipment of equipmentData.data) {
            try {
                const now = new Date();
                const formattedNow = now.toISOString().slice(0, 19).replace('T', ' ');

                await dataSource.query(`
          INSERT INTO equipment_base (
            id, name, base, level, price, type, image, intro, weight,
            req_level, req_strength, req_constitution, req_agility, req_intelligence,
            bonus_attack, bonus_hp, bonus_mp, bonus_defense, created_at, updated_at
          ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        `, [
                    equipment.id,
                    equipment.name,
                    equipment.base,
                    equipment.level,
                    equipment.price,
                    equipment.type,
                    equipment.image,
                    equipment.intro,
                    equipment.weight,
                    equipment.req_level,
                    equipment.req_strength,
                    equipment.req_constitution,
                    equipment.req_agility,
                    equipment.req_intelligence,
                    equipment.bonus_attack,
                    equipment.bonus_hp,
                    equipment.bonus_mp,
                    equipment.bonus_defense,
                    formattedNow,
                    formattedNow
                ]);

                successCount++;
                if (successCount % 5 === 0) {
                    console.log(`📊 已导入 ${successCount} 个装备...`);
                }
            } catch (error) {
                errorCount++;
                console.error(`❌ 导入装备 "${equipment.name}" 失败:`, error.message);
            }
        }

        console.log('\n📊 导入完成统计:');
        console.log(`✅ 成功导入: ${successCount} 个装备`);
        console.log(`❌ 导入失败: ${errorCount} 个装备`);

        // 验证导入结果
        console.log('\n🔍 验证导入结果...');
        const totalCount = await dataSource.query('SELECT COUNT(*) as count FROM equipment_base');
        console.log(`📊 数据库中总共有 ${totalCount[0].count} 个装备`);

        // 显示一些示例数据
        const sampleData = await dataSource.query(`
      SELECT id, name, base, level, type, bonus_attack, bonus_hp, bonus_mp, bonus_defense 
      FROM equipment_base 
      ORDER BY id 
      LIMIT 10
    `);

        console.log('\n📋 示例数据:');
        sampleData.forEach((equipment, index) => {
            console.log(`${index + 1}. ID: ${equipment.id}, 名称: ${equipment.name}, 基础: ${equipment.base}, 等级: ${equipment.level}, 类型: ${equipment.type}`);
            console.log(`   攻击: ${equipment.bonus_attack}, 血量: ${equipment.bonus_hp}, 魔法: ${equipment.bonus_mp}, 防御: ${equipment.bonus_defense}`);
        });

        // 按基础类型统计
        console.log('\n📊 按基础类型统计:');
        const baseStats = await dataSource.query(`
      SELECT base, COUNT(*) as count 
      FROM equipment_base 
      GROUP BY base 
      ORDER BY base
    `);

        baseStats.forEach((stat, index) => {
            console.log(`${index + 1}. 基础类型 ${stat.base}: ${stat.count} 个装备`);
        });

        // 按等级统计
        console.log('\n📊 按等级统计:');
        const levelStats = await dataSource.query(`
      SELECT level, COUNT(*) as count 
      FROM equipment_base 
      GROUP BY level 
      ORDER BY level
    `);

        levelStats.forEach((stat, index) => {
            console.log(`${index + 1}. 等级 ${stat.level}: ${stat.count} 个装备`);
        });

    } catch (error) {
        console.error('❌ 导入过程中发生错误:', error);
    } finally {
        if (dataSource.isInitialized) {
            await dataSource.destroy();
            console.log('🔌 数据库连接已关闭');
        }
    }
}

// 运行导入
importEquipmentBase().catch(console.error);

